<template>
    <div class="vehicle-add-page">
        <div class="page-title">修改车辆</div>

        <div class="form card">
            <div class="grid">
                <div class="form-item required">
                    <label class="label">厂牌型号：</label>
                    <input class="input" v-model.trim="form.brandModel" placeholder="请输入厂牌型号" />
                </div>

                <div class="form-item required">
                    <label class="label">车牌号：</label>
                    <input class="input" v-model.trim="form.plateNumber" placeholder="请输入车牌号" />
                </div>

                <div class="form-item required">
                    <label class="label">车辆类型：</label>
                    <select class="input" v-model="form.vehicleType">
                        <option value="" disabled>请选择车辆类型</option>
                        <option value="冷冻车">冷冻车</option>
                        <option value="货车">货车</option>
                        <option value="前四后八">前四后八</option>
                    </select>
                </div>

                <div class="form-item required">
                    <label class="label">司机姓名：</label>
                    <input class="input" v-model.trim="form.driverName" placeholder="请输入司机姓名" />
                </div>

                <div class="form-item required">
                    <label class="label">所属公司：</label>
                    <input class="input" v-model.trim="form.company" placeholder="请输入所属公司" />
                </div>

                <div class="form-item required size-group">
                    <label class="label">车 型：</label>
                    <input class="input size" type="text" v-model.trim="form.sizeLength" placeholder="长" />
                    <input class="input size" type="text" v-model.trim="form.sizeWidth" placeholder="宽" />
                    <input class="input size" type="text" v-model.trim="form.sizeHeight" placeholder="高" />
                </div>

                <div class="form-item required">
                    <label class="label">车辆颜色：</label>
                    <input class="input" v-model.trim="form.color" placeholder="请输入车辆颜色" />
                </div>

                <div class="form-item required">
                    <label class="label">购置日期：</label>
                    <input class="input" type="date" v-model="form.purchaseDate" placeholder="请选择购置日期" />
                </div>

                <div class="form-item required">
                    <label class="label">营运证号：</label>
                    <input class="input" v-model.trim="form.operationCert" placeholder="请输入营运证号" />
                </div>

                <div class="form-item required">
                    <label class="label">保险到期日期：</label>
                    <input class="input" type="date" v-model="form.insuranceExpire" placeholder="请选择保险到期日期" />
                </div>

                <div class="form-item required">
                    <label class="label">年检到期日期：</label>
                    <input class="input" type="date" v-model="form.annualInspectExpire" placeholder="请选择年检到期日期" />
                </div>

                <div class="form-item">
                    <label class="label">保养公里数设置：</label>
                    <input class="input" v-model.trim="form.maintenanceKm" placeholder="请输入保养公里数" />
                </div>

                <div class="form-item upload-item">
                    <label class="label">车辆照片：</label>
                    <div class="upload-box" @click="triggerVehicleInput">
                        <input ref="vehicleInput" class="file-input" type="file" accept="image/*"
                            @change="onVehicleImg" />
                        <div v-if="!vehiclePreview" class="uploader">
                            <div class="plus">+</div>
                            <div class="text">上传图片</div>
                        </div>
                        <img v-else :src="vehiclePreview" class="preview" alt="vehicle" />
                    </div>
                </div>

                <div class="form-item upload-item">
                    <label class="label">保险卡照片：</label>
                    <div class="upload-box" @click="triggerInsureInput">
                        <input ref="insureInput" class="file-input" type="file" accept="image/*"
                            @change="onInsureImg" />
                        <div v-if="!insurePreview" class="uploader">
                            <div class="plus">+</div>
                            <div class="text">上传图片</div>
                        </div>
                        <img v-else :src="insurePreview" class="preview" alt="insure" />
                    </div>
                </div>
            </div>

            <div class="form-actions">
                <button class="btn primary" :disabled="submitting" @click="handleSubmit">保存</button>
                <button class="btn" @click="handleCancel">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { uploadFileWithProgress, uploadFile } from '@/utils/fileUpload'
import { useRoute } from 'vue-router'
import { read, write } from '@/assets/Axios/axiosHttple'

interface UpdateVehicleDto {
    id?: number
    brandModel: string
    plateNumber: string
    vehicleType: string
    driverName: string
    company: string
    sizeLength: string
    sizeWidth: string
    sizeHeight: string
    color: string
    purchaseDate: string
    operationCert: string
    insuranceExpire: string
    annualInspectExpire: string
    maintenanceKm: string
}

const form = reactive<UpdateVehicleDto>({
    id: undefined,
    brandModel: '',
    plateNumber: '',
    vehicleType: '',
    driverName: '',
    company: '',
    sizeLength: '',
    sizeWidth: '',
    sizeHeight: '',
    color: '',
    purchaseDate: '',
    operationCert: '',
    insuranceExpire: '',
    annualInspectExpire: '',
    maintenanceKm: ''
})

const submitting = ref(false)
const vehicleInput = ref<HTMLInputElement | null>(null)
const insureInput = ref<HTMLInputElement | null>(null)
const vehiclePreview = ref<string>('')
const insurePreview = ref<string>('')
const vehicleFile = ref<File | null>(null)
const insureFile = ref<File | null>(null)
const MAX_FILE_SIZE = 5 * 1024 * 1024

function triggerVehicleInput() { if (vehicleInput.value) vehicleInput.value.click() }
function triggerInsureInput() { if (insureInput.value) insureInput.value.click() }
const route = useRoute()

function validate(): string | null {
    if (!form.brandModel) return '请输入厂牌型号'
    if (!form.plateNumber) return '请输入车牌号'
    if (!form.vehicleType) return '请选择车辆类型'
    if (!form.driverName) return '请输入司机姓名'
    if (!form.company) return '请输入所属公司'
    if (!form.sizeLength || !form.sizeWidth || !form.sizeHeight) return '请输入车型长宽高'
    if (!form.purchaseDate) return '请选择购置日期'
    if (!form.operationCert) return '请输入营运证号'
    if (!form.insuranceExpire) return '请选择保险到期日期'
    if (!form.annualInspectExpire) return '请选择年检到期日期'
    return null
}

function onVehicleImg(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return
    if (!file.type.startsWith('image/')) { alert('仅支持图片'); return }
    if (file.size > MAX_FILE_SIZE) { alert('图片不能大于5MB'); return }
    vehicleFile.value = file
    const reader = new FileReader()
    reader.onload = () => { vehiclePreview.value = String(reader.result || '') }
    reader.readAsDataURL(file)
}

function onInsureImg(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return
    if (!file.type.startsWith('image/')) { alert('仅支持图片'); return }
    if (file.size > MAX_FILE_SIZE) { alert('图片不能大于5MB'); return }
    insureFile.value = file
    const reader = new FileReader()
    reader.onload = () => { insurePreview.value = String(reader.result || '') }
    reader.readAsDataURL(file)
}

async function loadDetail(id: number) {
    try {
        const r1 = await read.get(`baseinforead/api/VehicleManagement/GetVehicleById/${encodeURIComponent(String(id))}`)
        const d = r1?.data?.data || null
        if (!d) return

        // 字段别名映射
        form.brandModel = String(
            d.brandModel ?? d.factoryModel ?? d.brandandModel ?? d.brandAndModel ?? d.factoryAndModel ?? ''
        )
        form.plateNumber = String(d.plateNumber ?? d.licensePlateNumber ?? '')
        form.driverName = String(d.driverName ?? d.ownerName ?? d.driver ?? d.driver_name ?? d.owner ?? '')
        form.company = String(
            d.company ?? d.companyName ?? d.affiliatedCompany ?? d.affiliationCompany ?? d.belongCompany ?? d.unitName ?? d.organization ?? d.orgName ?? ''
        )
        form.vehicleType = String(d.vehicleType ?? d.type ?? d.vehicleCategory ?? '')

        const sizeStr: string = String(d.size ?? d.vehicleSize ?? '')
        let len = '', wid = '', hei = ''
        if (sizeStr.includes('*')) {
            const parts = sizeStr.split('*').map((s: string) => s.trim())
            len = parts[0] ?? ''
            wid = parts[1] ?? ''
            hei = parts[2] ?? ''
        } else {
            len = String(d.long ?? '')
            wid = String(d.width ?? '')
            hei = String(d.height ?? '')
        }
        form.sizeLength = len
        form.sizeWidth = wid
        form.sizeHeight = hei

        form.color = String(d.color ?? d.vehicleColor ?? '')

        const toDateInput = (v: any) => {
            if (!v) return ''
            const dt = new Date(v)
            if (Number.isNaN(dt.getTime())) return ''
            const m = String(dt.getMonth() + 1).padStart(2, '0')
            const day = String(dt.getDate()).padStart(2, '0')
            return `${dt.getFullYear()}-${m}-${day}`
        }

        form.purchaseDate = toDateInput(d.purchaseDate)
        form.operationCert = String(d.operationCert ?? d.operationCertificateNumber ?? '')
        form.insuranceExpire = toDateInput(d.insuranceExpire ?? d.insuranceExpiryDate ?? d.insuranceExpirationDate)
        form.annualInspectExpire = toDateInput(d.annualInspectExpire ?? d.annualInspectionExpiryDate ?? d.annualInspectionExpirationDate)
        form.maintenanceKm = String(d.maintenanceKm ?? d.maintenanceMileageSetting ?? '')

        // 图片预览：兼容后端返回外链（http/https）、完整 data-url 或仅 base64 内容
        const toDataUrl = (s: any) => {
            if (!s) return ''
            const str = String(s).trim()
            if (!str) return ''
            if (str.startsWith('http://') || str.startsWith('https://')) return str
            if (str.startsWith('data:')) return str
            // 仅 Base64 内容时补全头
            return `data:image/*;base64,${str}`
        }
        // 支持后端同时返回数组或单值
        const firstOrJoin = (val: any) => {
            if (!val) return ''
            if (Array.isArray(val)) return val[0] ?? ''
            return val
        }
        vehiclePreview.value = toDataUrl(firstOrJoin(d.vehiclePhotos ?? d.vehiclePhoto))
        insurePreview.value = toDataUrl(firstOrJoin(d.insuranceCardPhotos ?? d.insuranceCardPhoto))
    } catch (e) {
        console.error('加载车辆详情失败', e)
    }
}

async function handleSubmit() {
    const msg = validate()
    if (msg) { alert(msg); return }
    submitting.value = true
    try {
        const toIso = (d: string) => d ? new Date(`${d}T00:00:00`).toISOString() : ''
        const stripDataUrl = (s: string) => s ? (s.includes(',') ? s.split(',')[1] : s) : ''
        // 先上传图片（若有本地file），优先使用上传返回的 URL；若上传失败则回退为 base64
        let vehicleUrl = ''
        let insureUrl = ''
        try {
            if (vehicleFile.value) vehicleUrl = await uploadFile(vehicleFile.value)
        } catch (e) { console.warn('车辆图片上传失败', e) }
        try {
            if (insureFile.value) insureUrl = await uploadFile(insureFile.value)
        } catch (e) { console.warn('保险卡图片上传失败', e) }

        const payload = {
            id: form.id ?? 0,
            brandandModel: String(form.brandModel || ''),
            licensePlateNumber: String(form.plateNumber || ''),
            ownerName: String(form.driverName || ''),
            unitName: String(form.company || ''),
            vehicleType: String(form.vehicleType || ''),
            vehicleColor: String(form.color || ''),
            purchaseDate: toIso(form.purchaseDate),
            long: String(form.sizeLength || ''),
            ratedLoadCapacity: Number(form.maintenanceKm) || 0,
            width: String(form.sizeWidth || ''),
            height: String(form.sizeHeight || ''),
            insuranceExpirationDate: toIso(form.insuranceExpire),
            volume: 0,
            operationCertificateNumber: Number(form.operationCert) || 0,
            annualInspectionExpirationDate: toIso(form.annualInspectExpire),
            maintenanceMileageSetting: Number(form.maintenanceKm) || 0,
            vehicleStatus: true,
            vehiclePhotos: vehicleUrl || stripDataUrl(vehiclePreview.value || ''),
            insuranceCardPhotos: insureUrl || stripDataUrl(insurePreview.value || ''),
            locationInformationStatus: true,
            lastModifiedBy: localStorage.getItem('username') || '张三'
        }

        const res = await write.post('baseinfowrite/api/VehicleManagement/Update', payload)
        const json: any = res?.data ?? {}
        if (res?.status === 200 && json?.code === 200) {
            alert('更新成功')
            window.location.href = '/GetVehicleManagement?refresh=1'
        } else {
            alert(json?.message || '更新失败')
        }
    } finally {
        submitting.value = false
    }
}

function handleCancel() { if (window.history.length > 1) window.history.back() }

onMounted(() => {
    const idParam = route.params.id || route.query.id
    const id = typeof idParam === 'string' ? Number(idParam) : Array.isArray(idParam) ? Number(idParam[0]) : Number(idParam)
    if (!Number.isNaN(id)) { form.id = id; loadDetail(id) }
})
</script>

<style scoped>
.vehicle-add-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.form {
    padding: 16px;
}

.grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(320px, 1fr));
    gap: 12px 24px;
    align-items: start;
    max-width: 1100px;
}

.form-item {
    display: flex;
    align-items: center;
}

.form-item.required .label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

.label {
    width: 120px;
    color: #666;
}

.input {
    flex: 1;
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
}

.size-group .size {
    width: 80px;
    margin-right: 8px;
}

.upload-item {
    align-items: center;
}

.upload-box {
    width: 210px;
    height: 160px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    background: #fafafa;
}

.file-input {
    position: absolute;
    opacity: 0;
    width: 0;
    height: 0;
}

.uploader {
    text-align: center;
    color: #909399;
}

.plus {
    font-size: 36px;
    line-height: 1;
}

.preview {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
}

.form-actions {
    margin-top: 18px;
    display: flex;
    gap: 10px;
}

.btn {
    height: 32px;
    padding: 0 16px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
